package edu.vital.energy.longevity.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import edu.vital.energy.longevity.domain.entity.SysMenu;
import edu.vital.energy.longevity.mapper.SysMenuMapper;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuService {
    
    private final SysMenuMapper sysMenuMapper;
    
    public MenuService(SysMenuMapper sysMenuMapper) {
        this.sysMenuMapper = sysMenuMapper;
    }
    
    public Map<String, Object> getMenuList() {
        try {
            // 查询所有菜单数据，不添加任何过滤条件
            List<SysMenu> allMenus = sysMenuMapper.selectList(null);
            System.out.println("数据库中所有菜单数量: " + allMenus.size());
            
            // 打印所有菜单信息，帮助排查问题
            for (SysMenu menu : allMenus) {
                System.out.println("菜单ID: " + menu.getId() + ", 名称: " + menu.getName() + 
                                  ", 路径: " + menu.getPath() + ", 父ID: " + menu.getParentId());
            }

            // 使用Set存储已处理的菜单ID，避免重复处理
            Set<Integer> processedMenuIds = new HashSet<>();
            
            // 筛选出顶级菜单，并按orderNum排序
            List<SysMenu> rootMenus = allMenus.stream()
                .filter(menu -> menu.getParentId() == null || menu.getParentId() == 0)
                .sorted(Comparator.comparing(SysMenu::getOrderNum))
                .collect(Collectors.toList());
            
            // 使用更严格的去重逻辑 - 只保留ID最小的那个
            Map<String, SysMenu> uniqueRootMenus = new LinkedHashMap<>();
            for (SysMenu menu : rootMenus) {
                String key = menu.getPath();  // 只用路径作为唯一键
                if (!uniqueRootMenus.containsKey(key) || 
                    menu.getId() < uniqueRootMenus.get(key).getId()) {
                    uniqueRootMenus.put(key, menu);
                }
                processedMenuIds.add(menu.getId());  // 记录已处理的ID
            }
            
            System.out.println("去重后顶级菜单数量: " + uniqueRootMenus.size());
            
            // 构建完整的菜单树
            List<Map<String, Object>> menuList = new ArrayList<>();
            for (SysMenu rootMenu : uniqueRootMenus.values()) {
                Map<String, Object> menuMap = convertMenuToMap(rootMenu);
                
                // 查找子菜单并去重
                Map<String, SysMenu> uniqueChildMenus = new LinkedHashMap<>();
                allMenus.stream()
                    .filter(menu -> rootMenu.getId().equals(menu.getParentId()) && !processedMenuIds.contains(menu.getId()))
                    .sorted(Comparator.comparing(SysMenu::getOrderNum))
                    .forEach(menu -> {
                        String key = menu.getPath();  // 只用路径作为唯一键
                        if (!uniqueChildMenus.containsKey(key) || 
                            menu.getId() < uniqueChildMenus.get(key).getId()) {
                            uniqueChildMenus.put(key, menu);
                        }
                        processedMenuIds.add(menu.getId());  // 记录已处理的ID
                    });
                
                if (!uniqueChildMenus.isEmpty()) {
                    List<Map<String, Object>> children = new ArrayList<>();
                    for (SysMenu childMenu : uniqueChildMenus.values()) {
                        Map<String, Object> childMap = convertMenuToMap(childMenu);
                        
                        // 处理三级菜单
                        List<Map<String, Object>> grandChildren = new ArrayList<>();
                        allMenus.stream()
                            .filter(menu -> childMenu.getId().equals(menu.getParentId()) && !processedMenuIds.contains(menu.getId()))
                            .sorted(Comparator.comparing(SysMenu::getOrderNum))
                            .forEach(menu -> {
                                grandChildren.add(convertMenuToMap(menu));
                                processedMenuIds.add(menu.getId());
                            });
                        
                        if (!grandChildren.isEmpty()) {
                            childMap.put("children", grandChildren);
                        }
                        
                        children.add(childMap);
                    }
                    menuMap.put("children", children);
                }
                
                menuList.add(menuMap);
            }
            
            // 构造返回格式
            Map<String, Object> data = new HashMap<>();
            data.put("list", menuList);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("result", "0");
            result.put("message", "Success");
            result.put("data", data);
            
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 1);
            result.put("result", "1");
            result.put("message", "Error: " + e.getMessage());
            result.put("data", null);
            
            return result;
        }
    }
    
    /**
     * 将菜单实体转换为Map
     */
    private Map<String, Object> convertMenuToMap(SysMenu menu) {
        Map<String, Object> menuMap = new HashMap<>();
        menuMap.put("path", menu.getPath());
        menuMap.put("name", menu.getName());
        menuMap.put("component", menu.getComponent());
        System.out.println(menu.getName()+menu.getPath());
        if (menu.getRedirect() != null) {
            menuMap.put("redirect", menu.getRedirect());
        }
        
        // 构建meta信息
        Map<String, Object> meta = new HashMap<>();
        
        // 处理标题的多语言
        Map<String, String> title = new HashMap<>();
        title.put("zh_CN", menu.getTitleZh());
        title.put("en_US", menu.getTitleEn());
        meta.put("title", title);
        
        // 处理图标
        if (menu.getIcon() != null) {
            meta.put("icon", menu.getIcon());
        }
        
        // 处理内嵌页面
        if (menu.getFrameSrc() != null) {
            meta.put("frameSrc", menu.getFrameSrc());
        }
        
        // 处理外链
        if (menu.getFrameBlank() != null && menu.getFrameBlank()) {
            meta.put("frameBlank", true);
        }
        
        menuMap.put("meta", meta);
        
        return menuMap;
    }
}